package com.imooc.apigateway.filter;

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SERVLET_DETECTION_FILTER_ORDER;

@Slf4j
public class RateLimiterFilter extends ZuulFilter {
    
    private static final RateLimiter RATE_LIMITER = RateLimiter.create(100);
    
    /**
     * 定义过滤器的类型 pre/post/../..
     * @return
     */
    @Override
    public String filterType() {
        return PRE_TYPE;
    }
    
    /**
     * 定义执行顺序,越小越先执行
     * @return
     */
    @Override
    public int filterOrder() {
        return SERVLET_DETECTION_FILTER_ORDER-1;
    }
    
    /**
     * 是否执行此过滤器
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }
    
    @Override
    public Object run() throws ZuulException {
        if (! RATE_LIMITER.tryAcquire()){
            log.error("RATE_LIMITER:{}","未获取到令牌");
            throw new RuntimeException("限流错误!!");
        }
        log.info("RATE_LIMITER:{}","成功获取到令牌,继续-->");
        return null;
    }
}
